// utils/websocket.js
const app = getApp()

class WebSocketManager {
  constructor() {
    this.socketTask = null
    this.isConnected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.messageHandlers = new Map()
    this.pendingMessages = []
  }

  // 连接WebSocket
  connect() {
    if (this.socketTask) {
      this.disconnect()
    }

    const token = app.globalData.token
    if (!token) {
      console.error('未登录，无法连接WebSocket')
      return
    }

    try {
      this.socketTask = wx.connectSocket({
        url: `wss://api.qingteng.com/ws?token=${token}`,
        header: {
          'content-type': 'application/json'
        }
      })

      this.setupEventHandlers()
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.handleReconnect()
    }
  }

  // 设置事件处理器
  setupEventHandlers() {
    this.socketTask.onOpen(() => {
      console.log('WebSocket连接成功')
      this.isConnected = true
      this.reconnectAttempts = 0
      
      // 发送待处理的消息
      this.sendPendingMessages()
      
      // 触发连接成功事件
      this.triggerEvent('connected')
    })

    this.socketTask.onMessage((res) => {
      try {
        const message = JSON.parse(res.data)
        this.handleMessage(message)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    })

    this.socketTask.onClose(() => {
      console.log('WebSocket连接关闭')
      this.isConnected = false
      this.triggerEvent('disconnected')
      
      // 尝试重连
      this.handleReconnect()
    })

    this.socketTask.onError((error) => {
      console.error('WebSocket连接错误:', error)
      this.isConnected = false
      this.triggerEvent('error', error)
    })
  }

  // 处理消息
  handleMessage(message) {
    const { type, data } = message
    
    // 触发特定类型的事件
    this.triggerEvent(type, data)
    
    // 触发通用消息事件
    this.triggerEvent('message', message)
  }

  // 发送消息
  send(type, data) {
    const message = {
      type,
      data,
      timestamp: Date.now()
    }

    if (this.isConnected && this.socketTask) {
      try {
        this.socketTask.send({
          data: JSON.stringify(message),
          success: () => {
            console.log('消息发送成功:', type)
          },
          fail: (error) => {
            console.error('消息发送失败:', error)
            // 添加到待处理队列
            this.pendingMessages.push(message)
          }
        })
      } catch (error) {
        console.error('发送消息异常:', error)
        this.pendingMessages.push(message)
      }
    } else {
      // 连接未建立，添加到待处理队列
      this.pendingMessages.push(message)
    }
  }

  // 发送待处理的消息
  sendPendingMessages() {
    while (this.pendingMessages.length > 0 && this.isConnected) {
      const message = this.pendingMessages.shift()
      this.send(message.type, message.data)
    }
  }

  // 断开连接
  disconnect() {
    if (this.socketTask) {
      this.socketTask.close()
      this.socketTask = null
    }
    this.isConnected = false
    this.reconnectAttempts = 0
  }

  // 处理重连
  handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数已达上限')
      return
    }

    this.reconnectAttempts++
    console.log(`尝试第${this.reconnectAttempts}次重连...`)

    setTimeout(() => {
      this.connect()
    }, this.reconnectInterval * this.reconnectAttempts)
  }

  // 注册事件处理器
  on(event, handler) {
    if (!this.messageHandlers.has(event)) {
      this.messageHandlers.set(event, [])
    }
    this.messageHandlers.get(event).push(handler)
  }

  // 移除事件处理器
  off(event, handler) {
    if (this.messageHandlers.has(event)) {
      const handlers = this.messageHandlers.get(event)
      const index = handlers.indexOf(handler)
      if (index !== -1) {
        handlers.splice(index, 1)
      }
    }
  }

  // 触发事件
  triggerEvent(event, data) {
    if (this.messageHandlers.has(event)) {
      const handlers = this.messageHandlers.get(event)
      handlers.forEach(handler => {
        try {
          handler(data)
        } catch (error) {
          console.error(`事件处理器执行错误 (${event}):`, error)
        }
      })
    }
  }

  // 获取连接状态
  getStatus() {
    return {
      isConnected: this.isConnected,
      reconnectAttempts: this.reconnectAttempts
    }
  }

  // 发送心跳
  sendHeartbeat() {
    if (this.isConnected) {
      this.send('heartbeat', { timestamp: Date.now() })
    }
  }

  // 开始心跳检测
  startHeartbeat(interval = 30000) {
    this.heartbeatInterval = setInterval(() => {
      this.sendHeartbeat()
    }, interval)
  }

  // 停止心跳检测
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }
}

// 创建单例实例
const websocketManager = new WebSocketManager()

// 导出实例
module.exports = websocketManager

// 常用消息类型常量
const MessageTypes = {
  // 聊天相关
  SEND_MESSAGE: 'send_message',
  NEW_MESSAGE: 'new_message',
  MESSAGE_READ: 'message_read',
  TYPING: 'typing',
  
  // 用户状态
  USER_ONLINE: 'user_online',
  USER_OFFLINE: 'user_offline',
  
  // 匹配相关
  NEW_MATCH: 'new_match',
  NEW_LIKE: 'new_like',
  NEW_VISITOR: 'new_visitor',
  
  // 系统消息
  SYSTEM_NOTIFICATION: 'system_notification',
  
  // 心跳
  HEARTBEAT: 'heartbeat'
}

// 导出消息类型
module.exports.MessageTypes = MessageTypes
